package com.duoec.magichour.core.web.freemarker.portlet.common;

import com.duoec.magichour.core.CommonConst;
import com.duoec.magichour.core.utils.FileUtils;
import com.duoec.magichour.core.web.freemarker.PortletException;
import com.duoec.magichour.core.web.freemarker.TemplateModelUtils;
import com.duoec.magichour.core.web.freemarker.model.BaseTemplateModel;
import com.duoec.magichour.core.web.freemarker.model.SortedVar;
import com.duoec.magichour.core.web.freemarker.model.StringVar;
import com.duoec.magichour.core.web.freemarker.portlet.Portlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 样式组件
 * Created by ycoe on 16/4/28.
 */
@Portlet("css")
public class CssPortlet extends ResourcePortlet {
    private static final Logger logger = LoggerFactory.getLogger(LayoutPortlet.class);

    private static final String CSS_DIR = "static_css";

    @Override
    public void loadData() throws PortletException {
        File css = getSourceFile();
        if (css != null) {
            resourceVars.addCss(css, order);
        }
    }

    private void renderStyle() throws PortletException {
        SortedVar cssVar = resourceVars.getCssSortedVar();

        if (cssVar != null) {
            renderToFile(cssVar);
        }
    }

    private void renderToFile(final SortedVar cssVar) {
        long lastModifyTime = cssVar.getLastModified();
        File cssDir = new File(CommonConst.TP_ASSETS_PATH + CSS_DIR);
        if (!cssDir.exists()) {
            cssDir.mkdir();
        }
        String cssFileName = CSS_DIR + "/" + getResourceName(lastModifyTime) + ".css";
        String cssFilePath = CommonConst.TP_ASSETS_PATH + cssFileName;
        File cssFile = new File(cssFilePath);
        if (!cssFile.exists()) {
            String content = TemplateModelUtils.renderToString(cssVar);
            try {
                FileUtils.writeStringToFile(new File(cssFilePath), content);
            } catch (IOException e) {
                logger.error("写入文件失败：{}", cssFilePath, e);
            }
        }

        String cssUrl = CommonConst.TP_ASSETS_URL + "/" + cssFileName;
        try {
            env.getOut().write("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + cssUrl + "\">");
        } catch (IOException e) {
            logger.error("写入样式链接[" + cssUrl + "]失败!", e);
        }
    }

    @Override
    protected void doRend(BaseTemplateModel model) throws PortletException {
        if (body != null && model != null && model instanceof StringVar) {
            long modifyTime = getTemplateLastModify();
            resourceVars.addCss(((StringVar) model).getContext(), order, modifyTime);
        }
        if (body == null && src == null) {
            renderStyle();
        }
    }
}
